package com.lmt.api;

import com.lmt.base.ResultData;
import com.lmt.entity.Audit;
import com.lmt.entity.ResourceTemp;
import com.lmt.entity.TagTemp;
import com.lmt.entity.search.ResourceTempSearch;
import com.lmt.service.AuditService;
import com.lmt.service.ResourceTempService;
import com.lmt.service.TagTempService;
import com.lmt.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@RestController
@RequestMapping("/ResourceTempApi")
public class ResourceTempApi {

	private Logger logger = LoggerFactory.getLogger(ResourceTempApi.class);

	private final RedisCacheUtil redisCacheUtil;

	private final FileUtil fileUtil;

	private final ResourceTempService resourceTempService;

	private final TagTempService tagTempService;

	private final AuditService auditService;

	@Autowired
	public ResourceTempApi(RedisCacheUtil redisCacheUtil, FileUtil fileUtil, ResourceTempService resourceTempService, TagTempService tagTempService, AuditService auditService) {
		this.redisCacheUtil = redisCacheUtil;
		this.fileUtil = fileUtil;
		this.resourceTempService = resourceTempService;
		this.tagTempService = tagTempService;
		this.auditService = auditService;
	}

	@RequestMapping("search")
	public ResultData search(@RequestBody ResourceTempSearch resourceTempSearch) {
		return this.resourceTempService.search(resourceTempSearch);
	}

	@SuppressWarnings("WeakerAccess")
    @RequestMapping("/upload")
	public ResultData upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
		// 保存待审核的资源数据
		String resourceMd5 = fileUtil.saveFile(multipartFile);
		if (null == resourceMd5) {
			return ResultUtil.newFail("资源保存失败，请重试或联系管理员");
		}
		Object saveResourceTempResult = this.saveResourceTemp(multipartFile, resourceMd5, request);
		if (saveResourceTempResult instanceof ResultData) {
			return (ResultData) saveResourceTempResult;
		}
		String resourceTempId = (String) saveResourceTempResult;
		this.saveResourceTempTags(request, resourceTempId);
		ResultData saveAuditDataResult = this.saveAuditData(resourceTempId);
		if (CheckResult.isFail(saveAuditDataResult)) {
			return saveAuditDataResult;
		}
		if (!fileUtil.renameFile(multipartFile, resourceTempId)) {
			return ResultUtil.newFail("文件重命名失败，请联系管理员");
		}
		return ResultUtil.newSuccess("上传资源成功");
	}

	@RequestMapping("/uploadFiles")
	public ResultData uploadFiles(HttpServletRequest request) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		for (MultipartFile multipartFile : files) {
			ResultData result = this.upload(multipartFile, request);
			if (CheckResult.isFail(result)) {
				return result;
			}
		}
		return ResultUtil.newSuccess("上传资源成功");
	}

	/**
	 * @apiNote 保存待审核数据
	 * @param resourceTempId 待审核资源ID
	 * @return ResultData
	 */
	private ResultData saveAuditData(String resourceTempId) {
		Audit audit = new Audit();
		audit.setObjId(resourceTempId);
		audit.setOperation(SystemConstant.AUDIT_OPERATION_ADD);
		audit.setStatus(SystemConstant.AUDIT_STATUS_WAIT);
		return this.auditService.save(audit);
	}

	/**
	 * @apiNote 保存待审核资源的标签
	 * @param request 包含标签参数的request
	 * @param resourceTempId 待审核资源ID
	 */
	private void saveResourceTempTags(HttpServletRequest request, String resourceTempId) {
		// 保存待审核资源的标签
		String tags = request.getParameter("tags");
		if (StringUtils.isEmpty(tags)) {
			return;
		}
		if (!StringUtils.isEmpty(tags)) {
			TagTemp tagTemp = new TagTemp();
			tagTemp.setResourceTempId(resourceTempId);
			tagTemp.setTag(tags);
			ResultData saveTagsResult = this.tagTempService.save(tagTemp);
			if (CheckResult.isFail(saveTagsResult)) {
				logger.error(
						"待审核资源 [ id = " + resourceTempId + " ] 标签保存失败：" + saveTagsResult.getMessage());
			}
		}
	}

	/**
	 * @apiNote 保存待审核资源
	 * @param resourceMd5 资源文件的MD5值
	 * @param request 带有待审核资源数据的request
	 * @return 保存成功返回待审核资源ID，保存失败返回Map
	 */
	private Object saveResourceTemp(MultipartFile multipartFile, String resourceMd5, HttpServletRequest request) {
		ResourceTemp resourceTemp = new ResourceTemp();
		String tokenId = request.getSession().getAttribute(SystemConstant.USER_LOGIN_EVIDENCE).toString();
		resourceTemp.setAuthorId(redisCacheUtil.getUserId(tokenId));
		resourceTemp.setMd5(resourceMd5);
		resourceTemp.setDesignation(multipartFile.getOriginalFilename());
		resourceTemp.setResourceType(request.getParameter("resourceType"));
		resourceTemp.setResourceSize(multipartFile.getSize() / 1024);
		String classifyId = request.getParameter("classifyId");
		if (!StringUtils.isEmpty(classifyId)) {
			resourceTemp.setClassifyId(classifyId);
		}
		String description = request.getParameter("description");
		if (!StringUtils.isEmpty(description)) {
			resourceTemp.setDescription(description);
		}
		ResultData result = this.resourceTempService.save(resourceTemp);
		if (CheckResult.isFail(result)) {
			return result;
		}
		return result.getData().toString();
	}
}
